const tbody = document.querySelector('tbody')
const provinceDom = document.querySelector('[name=province]')
const cityDom = document.querySelector('[name=city]')
const countyDom = document.querySelector('[name=county]')
const addForm = document.querySelector('.add-form')
const showModalBtn = document.querySelector('.show_modal_btn')
const addModal = document.querySelector('#addModal')
const addModalLabel = document.querySelector('#addModalLabel')

// 初始化
function init() {
    // 学员信息
    getstudentList()
    //省份选择
    getProvince()

    provinceDom.addEventListener('change', function (e) {
        // 有省份才获取
        if (provinceDom.value) getCity(provinceDom.value)
    })
    cityDom.addEventListener('change', function (e) {
        // 有省市才获取
        if (provinceDom.value && cityDom.value) getCounty(provinceDom.value, cityDom.value)
    })
}

init()

async function getstudentList() {
    const result = await axios({ url: '/student/list' })
    // console.log(result)

    const html = result.data.data.reduce((prev, item) => {
        const { id, name, sex, age, group, phone, salary, truesalary, province, city, county } = item
        //         {
        //     "id": 1009,
        //     "name": "卢秀英",
        //     "sex": "女",
        //     "age": 22,
        //     "group": 1,
        //     "phone": "15015037328",
        //     "salary": 8948,
        //     "truesalary": 17618,
        //     "province": "甘肃省",
        //     "city": "金昌市",
        //     "county": "金川区",
        //     "user_id": 23,
        //     "jing": 102.194089,
        //     "wei": 38.521085
        // }
        return prev + `
        <tr>
        <th scope="row">${id}</th>
        <td>${name}</td>
        <td>${sex}</td>
        <td>${age}</td>
        <td>${group}</td>
        <td>${phone}</td>
        <td>${salary}</td>
        <td>${truesalary}</td>
        <td>${province + city + county}</td>
        <td>
          <button type="button" class="btn btn-primary btn-sm edit-btn" data-id="${id}">修改</button>
          <button type="button" class="btn btn-danger btn-sm del-btn" data-id="${id}">删除</button>
        </td>
      </tr>
        `
    }, '')
    tbody.innerHTML = html
}
// 添加学员-显示模态框 点击
showModalBtn.addEventListener("click", function (e) {
    // 重置之前表单操作遗留的数据
    addForm.reset()
    addModalLabel.innerText = `录入新学员`
    $("#addModal").modal("show"); // 显示模态框
});
// 点击修改-删除获取学员信息
tbody.addEventListener('click', async function (e) {
    if (e.target.classList.contains('edit-btn')) {
    addModalLabel.innerText = `修改学员信息`
        $("#addModal").modal("show"); // 显示模态框
        //数据回填
        const id = e.target.dataset.id
        //获取对应id点击修改的学员信息回填
        const result = await axios({ url: '/student/one', params: { id } })
        // console.log(result)
        const data = result.data.data
        await getCity(data.province)
        await getCounty(data.province, data.city)
        /*         if (result.data.code === 0) {
                    delete data.id
                    delete data.user_id
                    delete data.jing
                    delete data.wei
                    // console.log(data)
                    for (const key in data) {
                        if (key === 'sex') {
                            addModal.querySelector(`[name=sex][value=${data[key]}]`).checked = true
                        } else {
                            addModal.querySelector(`[name=${key}]`).value = data[key]
                        }
                    }
                } */
        addForm.querySelector(`[name=sex][value=${data.sex}]`).checked=true
        // 性别单独拿出来处理
        // console.log( addForm.querySelectorAll('[name]'))        
        addForm.querySelectorAll('[name]').forEach(dom => {
       
            if (dom.name !== 'sex') {             
                addForm.querySelector(`[name=${dom.name}]`).value = data[dom.name]
            }
        })
    }else if (e.target.classList.contains('del-btn')) {
        if (confirm("是否要删除这条信息")) {
            const id=e.target.dataset.id    
            const result = await axios({ url: '/student/delete',method:'delete', params: {id} })

            if (result.data.code===0) {
            toastr.waring(result.data.message)
            // 删除后重新渲染
            getstudentList()
            }       
        }        
    }
})
// 表单提交事件，根据标题文本内容进行判断做修改或添加
addForm.addEventListener('submit', async function (e) {
    let result
    e.preventDefault()
    const data = serialize(addForm, { hash: true, empty: true })
    // console.log(data)
    // 修改
    if (addModalLabel.innerText === `修改学员信息`) {
        result = await axios({ url: '/student/update', method: 'put', data })
       
    }else if (addModalLabel.innerText = `录入新学员`) {
        // 录入传参不用id
        delete data.id
         result = await axios({ url: '/student/add', method: 'post', data })
    }
    
    console.log(result)
    if (result.data.code === 0) {
        toastr.success(result.data.message)
        // 重置表单信息
        //关闭模态框
        // 重新渲染数据
        addForm.reset()
        $("#addModal").modal("hide")
        getstudentList()

    }

})
// 重置表单，补充地址强重置
document.querySelector('[type=reset]').addEventListener("click", ()=>{
    cityDom.innerHTML=`<option selected value="">--市--</option>`
    countyDom.innerHTML=`<option selected value="">--县--</option>`
})

async function getProvince() {
    const result = await axios({
        url: '/geo/province',
    })
    console.log(result)
    provinceDom.innerHTML = result.data.reduce((prev, item) => {
        return prev + `<option  value="${item}">${item}</option>`
    }, '<option selected value="">--省--</option>')


}



async function getCity(provinceValue) {
    const result = await axios({
        url: '/geo/city',
        params: {
            pname: provinceValue,
        }
    })
    console.log(result)

    cityDom.innerHTML = result.data.reduce((prev, item) => {
        return prev + `<option  value="${item}">${item}</option>`
    }, '<option  value="">--市--</option>')
    // 重新选择省的时候县级数据要重置
    countyDom.innerHTML = `<option  value="">--县--</option>`

}


async function getCounty(provinceValue, cityValue) {
    const result = await axios({
        url: '/geo/county',
        params: {
            pname: provinceValue,
            cname: cityValue,
        }
    })
    console.log(result)
    countyDom.innerHTML = result.data.reduce((prev, item) => {
        return prev + `<option  value="${item}">${item}</option>`
    }, '<option selected value="">--县--</option>')

}



